<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>JS 刮刮乐</title>
  <style>
    body {
      margin: 0;
      display: flex;
      height: 100vh;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
    }
    .card {
      position: relative;
      width: 300px;
      height: 120px;
      background: #ffd700;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, .2);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      font-weight: bold;
      user-select: none;
    }
    canvas {
      position: absolute;
      left: 0;
      top: 0;
      border-radius: 12px;
      cursor: pointer;
    }
  </style>
</head>
<body>

<div class="card" id="card">
  <span>一等奖 100 元</span>
  <canvas id="mask" width="300" height="120"></canvas>
</div>

<script>
  /* 1. 初始化画布 */
  const canvas = document.getElementById('mask');
  const ctx = canvas.getContext('2d');
  const width = canvas.width;
  const height = canvas.height;

  // 填充灰色遮盖层
  ctx.fillStyle = '#999';
  ctx.fillRect(0, 0, width, height);
  ctx.font = '16px Arial';
  ctx.fillStyle = '#fff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText('刮一刮 赢大奖', width / 2, height / 2);

  /* 2. 设置刮刮效果参数 */
  ctx.globalCompositeOperation = 'destination-out';   // 关键：绘制部分会被擦除
  ctx.lineWidth = 30;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';

  let isDrawing = false;
  let lastX = 0;
  let lastY = 0;

  /* 3. 事件处理 */
  const getPos = (e) => {
    const rect = canvas.getBoundingClientRect();
    return [
      (e.clientX || e.touches[0].clientX) - rect.left,
      (e.clientY || e.touches[0].clientY) - rect.top
    ];
  };

  const start = (e) => {
    isDrawing = true;
    [lastX, lastY] = getPos(e);
  };

  const move = (e) => {
    if (!isDrawing) return;
    e.preventDefault();
    const [x, y] = getPos(e);
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(x, y);
    ctx.stroke();
    [lastX, lastY] = [x, y];
  };

  const end = () => {
    isDrawing = false;
    checkCleared();
  };

  /* 4. 计算已刮开面积 */
  function checkCleared() {
    const imageData = ctx.getImageData(0, 0, width, height);
    const pixels = imageData.data;
    let transparent = 0;
    for (let i = 3; i < pixels.length; i += 4) {
      if (pixels[i] < 128) transparent++;
    }
    const ratio = transparent / (width * height);
    if (ratio > 0.7) {
      canvas.style.display = 'none';  // 透明区域超过 70% 就隐藏遮盖层
    }
  }

  /* 5. 绑定鼠标 & 触摸事件 */
  canvas.addEventListener('mousedown', start);
  canvas.addEventListener('mousemove', move);
  canvas.addEventListener('mouseup', end);
  canvas.addEventListener('mouseleave', end);

  canvas.addEventListener('touchstart', start);
  canvas.addEventListener('touchmove', move);
  canvas.addEventListener('touchend', end);
</script>

</body>
</html>